import categoryApi from '@/api/categorys.js'

const state = {
  // 分类数据
  categories: [],
  // 当前选中的分类
  currentCategory: null,
  // 热门分类
  hotCategories: [],
  // 推荐分类
  recommendedCategories: [],
  // 分类树结构
  categoryTree: [],
  // 分类搜索历史
  searchHistory: [],
  // 分类加载状态
  loading: false
}

const getters = {
  // 获取所有分类
  allCategories: state => state.categories,
  // 获取当前选中的分类
  getCurrentCategory: state => state.currentCategory,
  // 获取热门分类
  getHotCategories: state => state.hotCategories,
  // 获取推荐分类
  getRecommendedCategories: state => state.recommendedCategories,
  // 获取分类树
  getCategoryTree: state => state.categoryTree,
  // 获取分类搜索历史
  getSearchHistory: state => state.searchHistory,
  // 获取加载状态
  isLoading: state => state.loading,
  // 根据ID获取分类
  getCategoryById: state => id => {
    return state.categories.find(category => category.id === id)
  },
  // 根据类型获取分类
  getCategoriesByType: state => type => {
    return state.categories.filter(category => category.type === type)
  },
  // 搜索分类
  searchCategories: state => keyword => {
    if (!keyword) return []
    return state.categories.filter(category =>
      category.title.includes(keyword) ||
      category.text.includes(keyword) ||
      category.name.includes(keyword)
    )
  }
}

const mutations = {
  // 设置分类数据
  SET_CATEGORIES(state, categories) {
    state.categories = categories
  },
  // 设置当前分类
  SET_CURRENT_CATEGORY(state, category) {
    state.currentCategory = category
  },
  // 设置热门分类
  SET_HOT_CATEGORIES(state, categories) {
    state.hotCategories = categories
  },
  // 设置推荐分类
  SET_RECOMMENDED_CATEGORIES(state, categories) {
    state.recommendedCategories = categories
  },
  // 设置分类树
  SET_CATEGORY_TREE(state, tree) {
    state.categoryTree = tree
  },
  // 添加搜索历史
  ADD_SEARCH_HISTORY(state, keyword) {
    // 移除重复的关键字
    state.searchHistory = state.searchHistory.filter(item => item !== keyword)
    // 添加到开头
    state.searchHistory.unshift(keyword)
    // 限制历史记录数量
    if (state.searchHistory.length > 10) {
      state.searchHistory = state.searchHistory.slice(0, 10)
    }
  },
  // 清空搜索历史
  CLEAR_SEARCH_HISTORY(state) {
    state.searchHistory = []
  },
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading
  }
}

const actions = {
  // 初始化分类数据
  async initCategories({ commit, dispatch }) {
    commit('SET_LOADING', true)
    try {
      // 从categorys.js获取分类数据 - 需要等待异步调用
      const categories = await categoryApi.getCategoryTree()
      commit('SET_CATEGORIES', categories)

      // 初始化热门分类
      let hotCategories = []
      categories.forEach(category => {
        if (category.hot) {
          hotCategories.push({
            id: category.id,
            name: category.name,
            title: category.title,
            text: category.text,
            icon: category.icon,
            type: category.type,
            hot: true
          })
        }
      })
      commit('SET_HOT_CATEGORIES', hotCategories)

      // 初始化推荐分类
      let recommendedCategories = []
      categories.forEach(category => {
        if (category.recommend) {
          recommendedCategories.push({
            id: category.id,
            name: category.name,
            title: category.title,
            text: category.text,
            icon: category.icon,
            type: category.type,
            hot: true
          })
        }
      })
      commit('SET_RECOMMENDED_CATEGORIES', recommendedCategories)

      return categories
    } catch (error) {
      console.error('初始化分类数据失败:', error)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 选择分类
  selectCategory({ commit, getters }, categoryId) {
    const category = getters.getCategoryById(categoryId)
    if (category) {
      commit('SET_CURRENT_CATEGORY', category)
      return category
    }
    return null
  },

  // 搜索分类
  searchCategories({ commit, getters }, keyword) {
    if (keyword && keyword.trim()) {
      commit('ADD_SEARCH_HISTORY', keyword.trim())
    }
    return getters.searchCategories(keyword)
  },

  // 清空搜索历史
  clearSearchHistory({ commit }) {
    commit('CLEAR_SEARCH_HISTORY')
  },

  // 刷新分类数据
  async refreshCategories({ dispatch }) {
    return await dispatch('initCategories')
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}